<?php


namespace App\Services;



use App\Models\Bid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Contracts\JWTSubject;
use App\Utils\Code;

class BidService extends BaseService
{

    /**
     * 创建
     * @param array $params
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|JWTSubject|null
     * @throws \Exception
     */
    public function store(array $params) {
        if (!$this->checkParams($params)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        if (Bid::where('bid_code', $params['bid_code'])->whereNull('deleted_at')->exists()) {
            throw new \Exception('该场次编号已经被使用', Code::EXIST_REPEAT);
        }
        if ((int)$params['status'] && Bid::whereNull('deleted_at')->where('status', 1)->exists()) {
            throw new \Exception('已存在进行中的场次', Code::PARAMETER_ERROR);
        }
        $userId = \Auth::id();
        return \DB::transaction(function () use ($params, $userId) {
            $model = new Bid();
            $model->user_id = $userId;
            $model->bid_code = $params['bid_code'];
            if (isset($params['bid_name']) && $params['bid_name']) {
                $model->bid_name = $params['bid_name'];
            }
            if (isset($params['remarks']) && $params['remarks']) {
                $model->remarks = $params['remarks'];
            }
            if (isset($params['status'])) {
                $model->status = (int)$params['status'];
            }
            if (isset($params['ended_at']) && $params['ended_at']) {
                $model->ended_at = $params['ended_at'];
            }
            if (isset($params['opened_at']) && $params['opened_at']) {
                $model->opened_at = $params['opened_at'];
            }
            $model->save();
            return $this->show($model->bid_id);
        });
    }

    /**
     * 验证参数
     * @param array $params
     * @param null $id
     * @param bool $isUpdate
     * @return array
     * @throws \Exception
     */
    private function checkParams(array $params, $isUpdate = false){
        $rules = [
            'bid_code' => ['bail', 'required'],
            'bid_name' => ['bail', 'nullable', 'string'],
            'remarks' => ['bail', 'nullable', 'string'],
            'status' => ['bail', 'integer', 'in:0,1'],
            'opened_at' => ['bail', 'nullable', 'date'],
            'ended_at' => ['bail', 'nullable', 'date']
        ];
        if ($isUpdate){
            // 删除必选条件
            foreach ($rules as $field => &$rule){
                if (isset($rule[1]) && $rule[1] == 'required') {
                    $rule[1] = 'nullable';
                }
            }
        }
        $validator = Validator::make($params, $rules, [
            'status.in' => '场次状态出错'
        ], [
            'bid_code' => '场次代码',
            'bid_name' => '场次名称',
            'remarks' => '场次备注',
            'status' => '场次状态',
            'opened_at' => '结束时间',
            'ended_at' => '开场时间'
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        return $params;
    }

    /**
     * 删除
     * @param $id
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|JWTSubject|null
     * @throws \Exception
     */
    public function destroy($id = null) {
        $model = Bid::where('bid_id', $id)->whereNull('deleted_at')->first();
        if (!$model) {
            throw new \Exception('该场次不存在或已被删除', Code::EXIST_REPEAT);
        }
        if ($model->status == 1) {
            throw new \Exception('该场次处于进行中状态，请先结束', Code::EXIST_REPEAT);
        }
        return true;
    }

    /**
     * 修改
     * @param array $params
     * @param $id
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|JWTSubject|null
     * @throws \Exception
     */
    public function update(array $params, $id = null) {
        if (!$this->checkParams($params, true)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        $model = Bid::where('bid_id', $id)->whereNull('deleted_at')->first();
        if (!$model) {
            throw new \Exception('该场次不存在或已被删除', Code::EXIST_REPEAT);
        }
        if ((int)$params['status'] && Bid::whereNull('deleted_at')->where('bid_id', '!=', $id)->where('status', 1)->exists()) {
            throw new \Exception('已存在进行中的场次', Code::PARAMETER_ERROR);
        }
        return \DB::transaction(function () use ($params, $model) {
            if (isset($params['bid_code']) && $params['bid_code']) {
                $model->bid_code = $params['bid_code'];
            }
            if (isset($params['bid_name']) && $params['bid_name']) {
                $model->bid_name = $params['bid_name'];
            }
            if (isset($params['remarks']) && $params['remarks']) {
                $model->remarks = $params['remarks'];
            }
            if (isset($params['status'])) {
                $model->status = (int)$params['status'];
            }
            if (isset($params['ended_at']) && $params['ended_at']) {
                $model->ended_at = $params['ended_at'];
            }
            if (isset($params['opened_at']) && $params['opened_at']) {
                $model->opened_at = $params['opened_at'];
            }
            $model->save();
            return $this->show($model->bid_id);
        });
    }

    /**
     * 查看详情
     * @param $id
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|JWTSubject|null
     * @throws \Exception
     */
    public function show($id = null) {
        $model = Bid::where('bid_id', $id)->whereNull('deleted_at')->first();
        if (!$model) {
            throw new \Exception('该场次不存在或已被删除', Code::EXIST_REPEAT);
        }
        return $model;
    }

    /**
     * 查看激活的场次
     * @param $id
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|JWTSubject|null
     * @throws \Exception
     */
    public function showActive() {
        $model = Bid::where('status', 1)->whereNull('deleted_at')->first();
        if (!$model) {
            throw new \Exception('未有进行中的场次', Code::EXIST_REPEAT);
        }
        return $model;
    }

    /**
     * 查看列表
     * @param array $params
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|JWTSubject|null
     * @throws \Exception
     */
    public function index(array $params) {
        $model = Bid::whereNull('deleted_at');
        if (isset($params['bid_code']) && $params['bid_code']) {
            $model = $model->where('bid_code', $params['bid_code']);
        }
        if (isset($params['bid_name']) && $params['bid_name']) {
            $model = $model->where('bid_name', 'like', '%'.$params['bid_name'].'%');
        }
        if (isset($params['remarks']) && $params['remarks']) {
            $model = $model->where('remarks', 'like', '%'.$params['remarks'].'%');
        }
        if (isset($params['status'])) {
            $model = $model->where('status', (int)$params['status']);
        }
        if (isset($params['created_at']) && $params['created_at'] && is_array($params['created_at'])) {
            if (isset($params['created_at'][0]) && $params['created_at'][0]) {
                $model = $model->where('created_at', '>=', $params['created_at'][0]);
            }
            if (isset($params['created_at'][1]) && $params['created_at'][1]) {
                $model = $model->where('created_at', '<=', $params['created_at'][1]);
            }
        }
        return $model->orderBy('status', 'desc')
            ->orderBy('bid_id', 'desc')
            ->paginate(isset($params['per_page']) ? (int)$params['per_page'] : null);
    }
}
